package com.schtwz.trip.core.extension

import android.content.Context
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import java.lang.reflect.Type

/**
 *@des: Gson 相关扩展
 *@author: created by yk
 *@date: 2020/5/27
 */

/** gson实例. */
val localGson: Gson by lazy {
    GsonBuilder().create()
}

/**
 * 对象转json字符.
 * @receiver T
 * @return String
 */
fun <T> T.toJson(): String = localGson.toJson(this)

/**
 * json字符转对象.
 * @receiver String
 * @return T?
 */
inline fun <reified T> String.toObj(): T? =
    kotlin.runCatching {
        localGson.fromJson(this, T::class.java)
    }.getOrNull()

/**
 * 字符串转对象.
 * @receiver String
 * @param typeOfT Type
 * @return T?
 */
fun <T> String.toObj(typeOfT: Type): T? =
    kotlin.runCatching {
        localGson.fromJson<T>(this, typeOfT)
    }.getOrNull()

/**
 * 从asset中读取json.
 * @receiver Context
 * @param fileName String
 * @param typeOfT Type
 * @return T?
 */
fun <T> Context.readJsonFromAsset(fileName: String, typeOfT: Type): T? =
    runCatching {
        assets.open(fileName).reader().readText().toObj<T>(typeOfT)
    }.getOrNull()